package com.ce.tag;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.jsp.JspWriter;

import net.sf.json.JSONObject;

import com.ce.framework.exception.AppException;
import com.ce.framework.util.LogUtil;
import com.ce.sys.dict.dao.po.SysDictItem;
import com.ce.util.DictUtil;
import com.ce.util.TreeNode;

public class DictSelectTag extends AbstractSelectTag {
	private static final long serialVersionUID = 1L;
	
	/** 字典项 */
	private String dictName;
	
	protected String type;
	
	List<TreeNode> getContentList() {
		List<SysDictItem> list = null;
		try {
			list = DictUtil.getDictListByName(dictName);
		} catch (AppException e) {
			LogUtil.logError(e);
		}
		List<TreeNode> res = new ArrayList<TreeNode>();
		for(SysDictItem item:list){
			res.add(new TreeNode(item.getVcItemNumber(),item.getVcItemName()));
		}
		return res;
	}

	private String getVal(String val){
		return val==null?"":val.replaceAll(",", "&#44;").replaceAll(":", "&#58;").replaceAll("'", "&#39;").replaceAll("\\r|\\n", "");
	}
	public void writeHtml(){
		if("srhdata".equals(type)){
			JspWriter out = pageContext.getOut();
			try {
				StringBuffer html = new StringBuffer();
				for(Option opt:optList){
					addDataOption(html, opt.getValue(), opt.getLabel());
				}
				out.print(html.length()>0?html.substring(1):"");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		else if("json".equals(type)){
			JspWriter out = pageContext.getOut();
			try {
				Map<String,String> map = new LinkedHashMap<String, String>();
				for(Option opt:optList){
					addJsonOption(map, opt.getValue(), opt.getLabel());
				}
				JSONObject obj = new JSONObject();
				obj.putAll(map);
				out.print(obj.toString());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		else{
			super.writeHtml();
		}
	}
	void addJsonOption(Map<String,String> map, String vlaue, String label) {
		if(useText){
			value = label;
		}
		map.put(vlaue, label);
	}

	void addDataOption(StringBuffer html, String vlaue, String label) {
		if(useText){
			value = label;
		}
		html.append(",").append(getVal(value)).append(":").append(getVal(label));
	}

	public String getDictName() {
		return dictName;
	}

	public void setDictName(String dictName) {
		this.dictName = dictName;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

}
